package com.hong610.net.http.client;

import java.io.File;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.message.BasicNameValuePair;

import com.hong610.net.enums.NetHandle;
import com.hong610.net.http.response.HandleResponse;

/**
 * 进行请求，将数据返回给HandleResponse同一处理
 * Created by Hong on 2016/12/31.
 */
public abstract class NetHttp extends NetHttpResponse {

	/**
	 * 无参数post请求
	 * @return String
	 * @throws Exception Exception
	 * @return String
	 * @throws Exception Exception
	 */
	public String doPost() throws Exception {
		HttpResponse response = super.post();
		return HandleResponse.handle(response, handle, charset);
	}

	/**
	 * 带参数post
	 * @param params BasicNameValuePair参数集合
	 * @return String
	 * @throws Exception Exception
	 */
	public String doPost(List<BasicNameValuePair> params) throws Exception {
		HttpResponse response = super.post(params);
		return HandleResponse.handle(response, handle, charset);
	}

	/**
	 * 数据流参数post
	 * @param parameterStream
	 * @return
	 * @throws Exception
	 */
	public String doPost(String parameterStream) throws Exception {
		HttpResponse response = super.post(parameterStream);
		return HandleResponse.handle(response, handle, charset);
	}

	/**
	 * 无参数get请求
	 * @return String
	 * @throws Exception Exception
	 */
	public String doGet() throws Exception {
		HttpResponse response = super.get(null);
		return HandleResponse.handle(response, handle, charset);
	}

	/**
	 * 带参数的get请求
	 * @param params 拼接
	 * @return String
	 * @throws Exception Exception
	 */
	public String doGet(String params) throws Exception {
		HttpResponse response = super.get(params);
		return HandleResponse.handle(response, handle, charset);
	}

	/**
	 * 带参数的get请求
	 * @param params BasicNameValuePair参数集合
	 * @return String
	 * @throws Exception Exception
	 */
	public String doGet(List<BasicNameValuePair> params) throws Exception {
		StringBuffer sb = new StringBuffer();
		for (BasicNameValuePair value : params) {
			sb.append(sb.indexOf("?") < 0 ? "?" : "&").append(value.getName()).append("=") .append(value.getValue());
		}
		HttpResponse response = this.get(sb.toString());
		return HandleResponse.handle(response, handle, charset);
	}

	/**
	 * 下载
	 * @param savePath 保存路径
	 * @return String
	 * @throws Exception Exception
	 */
	public String download(String savePath) throws Exception {
		HttpResponse response = super.get(null);
		handle = NetHandle.DOWNLOAD;
		return HandleResponse.handle(response, handle, charset, savePath);
	}

	/**
	 * 上传
	 * @param file 本地文件路径
	 * @return String
	 * @throws Exception Exception
	 */
	public String upload(String file) throws Exception {
		HttpResponse response = super.upload(new File(file));
		return HandleResponse.handle(response, handle, charset);
	}
	
}
